javascript debounce, trottle

마지막 수정일: 2025. 04. 09.

JAVASCRIPT
function debounce(func, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func(...args); 
    }, delay);
  };
}

function throttle(func, delay) {
  let lastCall = 0;
  return (...args) => {
    const now = new Date().getTime();
    if (now - lastCall >= delay) {
      lastCall = now;
      func(...args);
    }
  };
}

// 사용 예시
const search = function (query) {
  console.log(`Searching for: ${query}`);
};

const debouncedSearch = debounce(search, 300);

debouncedSearch("apple");
debouncedSearch("apple pie");
debouncedSearch("apple pie recipe"); // 이 값만 실행됨

const logScroll = function (position) {
  console.log(`Scrolled to: ${position}`);
};

const throttledLogScroll = throttle(logScroll, 1000);

throttledLogScroll(100);
throttledLogScroll(200); // 무시됨
setTimeout(() => throttledLogScroll(300), 500);  // 아직 1초 안 됨, 무시됨
setTimeout(() => throttledLogScroll(400), 1100); // 실행됨